import app from 'flarum/forum/app';
import Modal from "flarum/common/components/Modal";
import ItemList from "flarum/common/utils/ItemList";
import Button from 'flarum/common/components/Button';
import Stream from 'flarum/utils/Stream';

export default class ChangePasswordModal extends Modal{
  static isDismissible = true;
  oncreate(vnode) {
    super.oncreate(vnode);
    this.mobile = this.geTel(app.session.user.mobile())|| '';
    this.count= 60;
    this.code = Stream(this.attrs.code || '');
    this.password = Stream(this.attrs.password || '');
    this.repassword = Stream(this.attrs.repassword || '');
    this.sendingSms = false;
    this.liked = true;
    this.loading = false;
  }
  className() {
    return 'password-modal-class';
  }
  title() {
    return <p>更改密码</p>;
  }
  content() {
      return (
        <div className="Modal-body">
          {this.form().toArray()}
        </div>
      );
  }
  form(){
    const items = new ItemList();
    items.add(
        'mobile',
        <div className="Form-group">
          <label>手机号</label>
          <div>{this.mobile}</div>
        </div>,
        60
    )
    items.add(
      'msgcode',
      <div className="Form-group">
        <label>验证码</label>
        <view class="auth-line">
          <input 
            className="FormControl msgcode" 
            placeholder="请填写验证码" 
            type="number" 
            bidi={this.code}>

          </input>
          <button type="button" className="Button Button--primary"  
            onclick={this.sendCode.bind(this)}  disabled={this.sendingSms}>{
            this.liked
              ? '获取验证码'
              : `${this.count} 秒后重发`
          }</button>
        </view>
      </div>,
      60
    )
    items.add(
        'password',
        <div className="Form-group">
          <label>新密码</label>
          <input
            className="FormControl"
            placeholder="请填写新密码"
            type="password"
            bidi={this.password}
          />
        </div>,
        60
      )
    items.add(
        'repassword',
        <div className="Form-group">
          <label>确认新密码</label>
          <input
            className="FormControl"
            placeholder="请填写新密码"
            type="password"
            bidi={this.repassword}
          />
        </div>,
        60
      )
    items.add(
      'submit',
      <div className="Form-group">
        {Button.component(
          {
            className: 'Button Button--primary',
            type: 'submit',
            loading: this.loading,
          },
          '立即修改'
        )}
      </div>,
      -10
    );  
    return items;
  }
  geTel(tel){
    var reg = /^(\d{3})\d{4}(\d{4})$/;
    return tel.replace(reg, "$1****$2");
  }
  countDown() {
    if (this.count === 1) {
      this.count = 60;
      this.liked = true;
      this.sendingSms = false;
    } else {
      this.count = this.count -1;
      this.liked = false;
      setTimeout(this.countDown.bind(this), 1000);
    }
    m.redraw();
  }
  sendCode(){
    if (!this.liked) {
      return;
    }
    this.sendingSms = true;
    app.request({
        method: 'POST',
        url: app.forum.attribute('apiUrl') + '/sendchangecode',
        body: {},
        errorHandler: this.onerror.bind(this),
      })
      .then(() => {
        this.countDown();
      });
  }
  onerror(error) {
    error.alert.content = error.response;
    super.onerror(error);
    this.sendingSms = false;
    console.log('err');
  }
  isMobile(value){
    return /^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value);
  }
  onsubmit(e) {
    e.preventDefault();
    this.loading = true;
    if(this.password()==""){
        app.alerts.show({ type: 'error' },"请输入密码！");
        return ;
    }
    if(this.repassword()!==this.password()){
        app.alerts.show({ type: 'error' },"输入密码不一致！");
        return ;
    }
    app
      .request({
        method: 'POST',
        url: app.forum.attribute('apiUrl') + '/changePwd',
        body: { 
            pwd: this.password(),
            code: this.code(),
        },
        errorHandler: this.onerror.bind(this),
      })
      .then(() => {
        app.modal.close()
        app.alerts.show({ type: 'success' },"修改成功");
        m.redraw();
      })
      .catch(() => {})
      .then(this.loaded.bind(this));
  }
}
